﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ERP.WebUI
{
    public class ModulePermissionRepository 
    {
        private EFDbContext db = new EFDbContext();
        public IQueryable<ModulePermission> ModulePermissions
        {
            get { return db.ModulePermissions; }
        }

        public OperationResult SetButton(PermissionButtonModel model)
        {
            #region Add & Update
            var oldDataList = ModulePermissions.Where(t => t.ModuleId == model.ModuleId && t.IsDeleted == false).Select(t => t.PermissionId);
            var newDataList = model.SelectedButtonList.ToList();
            var intersectIds = oldDataList.Intersect(newDataList).ToList(); // Same Ids
            var updateIds = oldDataList.Except(intersectIds).ToList(); // Remove Ids
            var addIds = newDataList.Except(oldDataList).ToList(); // Add Ids
            //逻辑删除
            foreach (var removeId in updateIds)
            {
                var updateEntity = ModulePermissions.FirstOrDefault(t => t.ModuleId == model.ModuleId && t.PermissionId == removeId && t.IsDeleted == false);
                if (updateEntity != null)
                {
                    updateEntity.IsDeleted = true;
                    db.Set<ModulePermission>().Attach(updateEntity);
                    db.Entry<ModulePermission>(updateEntity).State = EntityState.Modified;
                    db.SaveChanges();
                }

            }
            //插入 & 更新
            foreach (var addId in addIds)
            {
                var updateEntity = ModulePermissions.FirstOrDefault(t => t.ModuleId == model.ModuleId && t.PermissionId == addId && t.IsDeleted == true);
                if (updateEntity != null)
                {
                    updateEntity.IsDeleted = false;
                    db.Set<ModulePermission>().Attach(updateEntity);
                    db.Entry<ModulePermission>(updateEntity).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    var addEntity = new ModulePermission { ModuleId = model.ModuleId, PermissionId = addId };
                    var user = SessionHelper.GetSession("CurrentUser") as User;
                    addEntity.CreateId = user.Id;
                    addEntity.CreateBy = user.LoginName;
                    addEntity.CreateTime = DateTime.Now;
                    addEntity.ModifyId = user.Id;
                    addEntity.ModifyBy = user.LoginName;
                    addEntity.ModifyTime = DateTime.Now;
                    db.Entry<ModulePermission>(addEntity).State = EntityState.Added;
                    db.SaveChanges();
                }
            }
            #endregion

            return new OperationResult(OperationResultType.Success, "设置成功");
        }
    }
}